package com.example.wasaimovie.Controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.wasaimovie.Annotation.DisableBaseResponse;
import com.example.wasaimovie.Model.entity.User;
import com.example.wasaimovie.Model.support.ResponseResult;
import com.example.wasaimovie.Service.Impl.UserServiceImpl;
import com.example.wasaimovie.Service.UserService;
import com.example.wasaimovie.Util.JwtTokenUtil;
import com.example.wasaimovie.Util.MD5Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.apache.commons.lang3.RandomStringUtils;

import javax.jws.soap.SOAPBinding;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/api/user")
@CrossOrigin
@Slf4j
public class UserController {
    @Autowired
    UserService service;

    @Value("${movie.image.url.path}")
    String url;

    /**
     * 登录接口
     * @param user 用户信息
     * @return 登录信息
     */
    @DisableBaseResponse
    @PostMapping("/login")
    public ResponseResult<Map<String, Object>> login(@RequestBody User user){
        log.info("UserController --> register" + user);
        ResponseResult<Map<String, Object>> result = null;
        result = service.login(user);
        return result;
    }

    /**
     * 注册接口
     * @param user 注册的用户信息
     */
    @DisableBaseResponse
    @PostMapping("/register")
    public ResponseResult<Map<String, Object>> register(@RequestBody User user){
        log.info("UserController --> register" + user);
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("username", user.getUsername());
        if (!service.list(qw).isEmpty()){
            // 该用户已经存在
            return new ResponseResult<>(401, "该用户已存在");
        }

        ResponseResult<Map<String, Object>>  result = null;
        user.setId(UUID.randomUUID().toString());
        result = service.register(user);
        return result;
    }

    /**
     * 按照ID获取用户信息
     * @param id 查询的用户ID
     * @return 返回用户信息
     */
    @CrossOrigin
    @PostMapping("/{id}")
    public User getUserInfoById(@PathVariable String id){
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("id", id);
        User user = service.list(qw).get(0);
        user.setAvatar(url + user.getAvatar());
        return user;
    }

    /**
     * 查询用户信息
     * @param id 用户id
     * @return 用户详细信息
     */
    @GetMapping("/{id}")
    @CrossOrigin
    public User getUserMsg(@PathVariable String id){
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("id", id);
        List<User> list = service.list(qw);
        User user = null;
        if (!list.isEmpty()){
            user = list.get(0);
            user.setAvatar(url + user.getAvatar());
        }
        return user;
    }

    /**
     * 修改用户信息
     * @param user 用户信息，根据主键进行修改
     * @return 是否修改成功
     */
    @PutMapping("")
    @CrossOrigin
    @DisableBaseResponse
    public ResponseResult<Object> updateUserMsg(@RequestBody User user){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        UpdateWrapper<User> qw = new UpdateWrapper<>();
        if (!("".equals(user.getPassword()) || user.getPassword() == null)) {
            // 用户密码加密
            String salt = RandomStringUtils.randomAlphabetic(10);
            int saltIndex = (int) (Math.random() * 10);
            user.setPassword(MD5Util.md5To32String(user.getPassword(), salt, saltIndex));
            qw.set("password", user.getPassword());
            qw.set("user_salt", salt);
            qw.set("salt_index", saltIndex);
        }
        qw.eq("id", user.getId());
        user.setAvatar(user.getAvatar().substring(user.getAvatar().lastIndexOf('/') + 1));
        qw.set("nickname", user.getNickname());
        qw.set("avatar", user.getAvatar());
        qw.set("email", user.getEmail());
        qw.set("birthday", user.getBirthday());
        qw.set("gender", user.getGender());
        qw.set("info", user.getInfo());
        qw.set("update_time", format.format(new Date()));
        if (service.update(qw)){
            return new ResponseResult<>(200, null);
        }
        return new ResponseResult<>(400, "修改失败");
    }

    /**
     * 获取所有用户信息
     * @return
     */
    @GetMapping("")
    @CrossOrigin
    public List<User> getAllUser(){
        return service.list();
    }

    @DeleteMapping("/delete/{id}")
    @CrossOrigin
    @DisableBaseResponse
    public ResponseResult<Object> deleteUser(@PathVariable String id){
        boolean b = service.removeById(id);
        if (b){
            return new ResponseResult<>(200, null);
        }
        return new ResponseResult<>(400, "删除失败");
    }
}
